import React, { Component, memo } from 'react';
import { getPartyDetail } from '../../api/index';
import { Modal, Toast } from 'antd-mobile';
import TimeAddress from './time-address';
import { smartStatus } from '../../util/StatusUtil';
import { setImageById } from '../../util/imageUtil';
import Tab from './tab';
import { loginNext } from '../../util/login';
import { RouteComponentProps } from 'react-router-dom';
const alert = Modal.alert;
interface IProps extends RouteComponentProps {
  className?: string;
  match: any;
}
interface IState {
  data?: any;
  classImageType: string;
  party: any;
  status: any;
  imgStatus: string;
  webReserveStatus: any;
  punishmentRecord:any

}


async function getData(id: string) {
  return new Promise((reply: any, reject) => {
    const barcode = sessionStorage.getItem('barcode') || 'undefined';
    getPartyDetail({ barcode, id })
      .then((response: any) => {
        const data = response.data;
        const party = data['party'];
        const status = smartStatus(data);
        const imgStatus = 'status' + status.code;
        data.status = status;
        data.imgStatus = imgStatus;
        reply(data);
      })
      .catch((e) => {
        console.log(e);
        reject({});
      });
  });
}
async function loadImage(id: string) {
  return new Promise((reply, reject) => {
    setImageById(id).then((res: any) => {
      reply(res);
    });
  });
}
class MyComponent extends Component<IProps, IState> {
  constructor(props: IProps) {
    super(props);
    this.state = {
      data: {},
      classImageType: '',
      party: {},
      status: {},
      imgStatus: 'status0',
      webReserveStatus:{},
      punishmentRecord:{}
    };
  }

  componentDidMount() {
    const {
      match: {
        params: { id },
      },
    } = this.props;
    this.loadData(id).then((r) => {
      this.setState(r);
    });
  }

  async loadData(id: string) {
    let party: any = {};
    let data: any = {};
    let punishmentRecord:any ={}
    await getData(id).then((response: any) => {
      data = response;
      party = data['party'];
      punishmentRecord=data['punishmentRecord']
    });
    const status = data.status;
    const imgStatus = data.imgStatus;
    await loadImage(party.imageId)
      .then((res: any) => {
        party['image'] = res;
      })
      .catch((e) => e);
    await loadImage(party.venuePicturesId)
      .then((res: any) => {
        party['venuePicturesImage'] = res;
      })
      .catch((e) => e);
    sessionStorage.setItem(party.id, JSON.stringify(party));
    let webReserveStatus = null;
    if(!!data['webReserveStatus']){
       webReserveStatus = data['webReserveStatus']
     if(!webReserveStatus.isReserve && webReserveStatus.remaining > 0){
                Toast.info("你正在排队报名这个活动!")
     }
    }
    return {
      webReserveStatus,
      party,
      data,
      status,
      imgStatus,
      punishmentRecord
    };
  }

  buttonState = () => {
    const then = this;
    const { history } = this.props;
    if (this.state.status) {
      const buttionStatus = this.state.status;
      if (buttionStatus.status) {
        return (
          <label
            className="actfix-apply"
            onClick={() => {
              
              const user = sessionStorage.getItem('user');
              const punishmentRecord =then.state.punishmentRecord;
              if(!!punishmentRecord && punishmentRecord.status==="1"){
                Toast.fail(punishmentRecord.foulDescription,3);
                return false
              }
              if (user != null) {
                if(!then.state.webReserveStatus.isReserve && then.state.webReserveStatus.remaining > 0){
                  Toast.fail("你正在排队报名这个活动!");
                  return false
                } 
               const response=then.state.data;
             
               const reserveAmount = response.reserveAmount;
               const party = response.party;
               
               const quota = party.quota;
               if(reserveAmount >= quota){
                alert('提示', '当前报名人数已经达到上限, 你确定要排队报名这个活动吗? ', [
                  { text: '取消', onPress: () => console.log('cancel') },
                  {
                    text: '好',
                    onPress: () =>
                      new Promise((resolve) => {
                        //Toast.info('onPress Promise', 1);
                        setTimeout(resolve, 100);
                        history.push('/party_reserve_queue/' + then.state.party.id);
                      }),
                  },
                ])
               }else{
                history.push('/party_reserve/' + then.state.party.id);
               }
              } else {
                loginNext(then, function () {
                  history.go(0);
                 });
              }
            }}>
            {buttionStatus.description}
          </label>
        );
      } else {
        if (buttionStatus.description === '进行中') {
          return <label className="actfix-apply">{buttionStatus.description}</label>;
        } else {
          return (
            <label className="actfix-apply" style={{ background: '#cccccc' }}>
              {buttionStatus.description}
            </label>
          );
        }
      }
    }
  };
  render() {
    return (
      <div>
        <div className="activity-top">
          <div className="tj-actlist-img activity-bigimg">
            <img
              id={this.state.party.imageId}
              src={this.state.party.image}
              alt={this.state.party.partyName || `图片加载中...`}
            />
            <i className={this.state.imgStatus}></i>
          </div>
        </div>
        <TimeAddress party={this.state.party} data={this.state.data}></TimeAddress>
        <div className="activity-bottom">

          <Tab depict={this.state.party.depict} history={this.props.history} venueImage={this.state.party.venuePicturesImage} partyId={this.state.party.id} />
        </div>
        <div className="actfix-b">
          <ul className="actfix-list clearfix">
            <li>
              <a className="act-yan">
                <i></i>
                <p>{this.state.data.pageViewAmount}</p>
              </a>
            </li>
          </ul>
          {this.buttonState()}
        </div>
      </div>
    );
  }
}

export default memo(MyComponent);
